package com.demo.zookeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;

public class ZookeeperConnection {
	
	private static String host = "192.168.6.120:2181";

	private static ZooKeeper zk;

	final static CountDownLatch countDownLatch = new CountDownLatch(1);

	public static ZooKeeper connect() throws IOException, InterruptedException {
		zk = new ZooKeeper(host, 6000, new Watcher() {
			public void process(WatchedEvent event) {
				if (event.getState() == KeeperState.SyncConnected) {
					countDownLatch.countDown();
				}
			}
		});
		countDownLatch.await();
		System.out.println("zookeeper connect ok.");
		return zk;
	}

	public static void close() throws InterruptedException {
		zk.close();
	}
	
	public static void main(String[] args) throws IOException, InterruptedException {
		ZookeeperConnection.connect();
	}
}
